package 反转链表;

import 其他.DataStructure.ListNode;
import org.junit.Test;

/*
    做完题一定写入表格
    tmp= tmp.n= 不会冲突覆盖的
    无论后序/while: 最后都要删1—>2
*/
public class a_最基本的反转链表206 {
    @Test
    public void test() {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        l1.next=l2;l2.next=l3;l3.next=l4;
        ListNode resH = reverseList_while(l1);
        System.out.println(1);
    }

    ListNode newHead;
    public ListNode reverseList_back(ListNode h) {
        //空
        if(h==null){
            return null;
        }
        ListNode head = h;
        back(head);
        head.next = null;
        return newHead;
    }
    private ListNode back(ListNode h) {
        //看图的4
        if(h.next==null){
            newHead = h;
            return h;
        }
        back(h.next).next = h;
        return h;
    }

    //while迭代
    public ListNode reverseList_while(ListNode h) {
        ListNode fir = h;
        if(h==null){
            return null;
        }
        ListNode sec = h.next;
        //因为我后面要 sec->fir
        if(h.next==null){
            return h;
        }

        while(sec!=null){
            ListNode tmp = sec.next;
            sec.next = fir;
            fir=sec; sec=tmp;
        }
        h.next = null;
        //fir恰好为4，sec=null
        return fir;
    }
}
